package handler

import (
	"context"
	"fmt"
	"gitee.com/zaiqiang231/go-base-app/base_app/store"
	"gitee.com/zaiqiang231/go-base-app/example/model"
	"gitee.com/zaiqiang231/go-base-app/example/rpc/proto"
	"gorm.io/gorm"
	"sync"
)

var (
	testSever     *TestServer
	oncePostSever sync.Once
)

type TestServer struct {
}

func GetTestServer() (*TestServer, error) {
	oncePostSever.Do(func() {
		testSever = &TestServer{}
	})

	if testSever == nil {
		return nil, fmt.Errorf("got nil server")
	}

	return testSever, nil
}

func (s *TestServer) GetTestModel(ctx context.Context, r *proto.TestModelInfoRequest) (*proto.TestModelInfoResponse, error) {
	var err error
	var target = model.TestModel{}
	store.GetDataStore().Execute(func(db *gorm.DB) {
		err = db.Transaction(func(tx *gorm.DB) error {
			return tx.Model(&model.TestModel{}).Where("name = ?", r.GetName()).First(&target).Error
		})
	})
	if err != nil {
		return nil, err
	}
	response := proto.TestModelInfoResponse{}
	response.Data = &proto.TestModel{
		Name: target.Name,
		Age:  target.Age,
		Sex:  target.Sex,
	}
	return &response, nil
}
